package com.easepal802s.project.ui.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.core.content.ContextCompat;

import android.util.Log;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.easepal802s.project.R;
import com.easepal802s.project.ble.BleController;
import com.easepal802s.project.ble.BluetoothDeviceAdapter;
import com.easepal802s.project.ble.BtDevice;
import com.easepal802s.project.ui.presenter.MBasePresenter;
import com.easepal802s.project.view.alertView.AlertView;
import com.easepal802s.project.view.alertView.OnItemClickListener;
import com.easepal802s.project.view.kprogresshud.KProgressHUD;
import com.example.reslib.utils.DisplayUtil;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

import static android.os.Build.VERSION_CODES.M;

/**
 * Created by FHB on 2018/3/22.
 */
public abstract class BaseMvpTestActivity<T, Act> extends RxAppCompatActivity {
    public T mPresenter;
    public MBasePresenter mBasePresenter;
    private AlertView alertViewBt;
    public KProgressHUD kProgressHUD;
    private BluetoothDeviceAdapter mBtListAdapter;
    private ListView deviceList;

    private Act mActivity;
    private MyHandler mHandle;
    public final static int SCAN_LIST = 100;
    public final static int DO_SCAN = 101;
    private AlertView alertView;
    //自定义的打开 Bluetooth 的请求码，与 onActivityResult 中返回的 requestCode 匹配。
    private static final int REQUEST_CODE_BLUETOOTH_ON = 1313;
    public List<BtDevice> mDeviceList = new ArrayList<>();
    // Bluetooth 设备可见时间，单位：秒。
    private static final int BLUETOOTH_DISCOVERABLE_DURATION = 120;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_ON:
                            break;
                        case BluetoothAdapter.STATE_OFF:
//                            BleController.getInst().setConnect(CONNECT_BREAK);
//                           BleController.getInst().connectBreak();

                            break;
                    }
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mPresenter == null) {
            mPresenter = initPresenter();
            mBasePresenter = (MBasePresenter) mPresenter;
        }
        mActivity = initActivity();
        registerReceiver(mReceiver, makeFilter());
        mHandle = new MyHandler(this);
        kProgressHUD = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
        kProgressHUD.setCanListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

                if (BleController.getInst().getConnectState() == BleController.SCANNING) {
                    Log.e("stopScan", "onBackPressed");
                    BleController.getInst().stopScan();
                }

            }
        });
        initCreateView(savedInstanceState);
    }

    private IntentFilter makeFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        return filter;
    }


    public void ShowBTListDialog(final List<BtDevice> list) {

        if (alertViewBt == null) {
            alertViewBt = new AlertView("选择设备", null, "取消",
                    new String[]{"确定"}, null, this,
                    AlertView.Style.Alert, "刷新",
                    new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position == -1) {
                                BleController.getInst().stopScan();
                            } else if (position == -2) {
                                //刷新蓝牙设备================
                                // alertViewBt.dismiss();
                                BleController.getInst().scanDevice();
                            } else {
                                // 连接蓝牙
                                boolean isGetSelect = false;
                                for (int i = 0; i < list.size(); i++) {
                                    if (list.get(i).isSelect()) {
                                        isGetSelect = true;
                                        BleController.getInst().stopScan();
                                        BleController.getInst().connectDevice(list.get(i).getBluetoothDevice());
                                        // list.get(i).setSelect(false);
                                    }
                                }
                                if (!isGetSelect) {
                                    showToast(R.string.bluetoothdevice_not_select);
                                }
                            }
                        }
                    });
            mBtListAdapter = new BluetoothDeviceAdapter(this, list);
            deviceList = new ListView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DisplayUtil.dp2px(this, 200));
            deviceList.setLayoutParams(layoutParams);
            deviceList.setAdapter(mBtListAdapter);
            alertViewBt.addExtView(deviceList);
        }
        mBtListAdapter.setBtList(list);
        alertViewBt.show();
        mBtListAdapter.notifyDataSetChanged();

    }

    public void showkProgress(int resID) {
//        canclekProgress();
        kProgressHUD.setLabel(getString(resID));
        kProgressHUD.show();
    }

    public void canclekProgress() {
        if (kProgressHUD != null && kProgressHUD.isShowing()) {
            kProgressHUD.dismiss();
        }

    }


    public void showToast(int resID) {
        Toast.makeText(this, getString(resID), Toast.LENGTH_SHORT).show();
    }


    public void showsAlert(int resId, final boolean isSendCommand) {
        if (alertView == null) {
            Log.e("showsAlert", "111");
            alertView = new AlertView(getString(R.string.prompts), getString(resId), null, new String[]{getString(R.string.sure)}, null, this
                    , AlertView.Style.Alert,
                    new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (isSendCommand) {
//                                DataService.getInstance().sendSingleData(BleConstant.STOP_QUCICKLY,true);

                            }
                        }
                    });
        } else {
            Log.e("showsAlert", "222");
            alertView.setAlertMsg(getString(resId));
        }
        if (!alertView.isShowing()) {
            Log.e("showsAlert", "333");
            alertView.show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();

    }

    public void showBleList() {
        mHandle.obtainMessage(SCAN_LIST).sendToTarget();
    }

    public void onMessageEvent() {
        //搜索前的权限判断。
        if (Build.VERSION.SDK_INT >= M && ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            PermissionGen.with((BaseMvpTestActivity) mActivity)
                    .addRequestCode(100)
                    .permissions(Manifest.permission.ACCESS_COARSE_LOCATION)
                    .request();
        } else {
            if (BleManager.getInstance().isBlueEnable()) {
                BleController.getInst().scanDevice();
            } else {
                turnOnBluetooth();
            }


        }
    }

    @PermissionSuccess(requestCode = 100)
    public void onPermissionSuccess() {

    }

    @PermissionFail(requestCode = 100)
    private void onPermissionFail() {
        Toast.makeText(this, getString(R.string.permissionDenied), Toast.LENGTH_SHORT).show();
        //Toast.makeText(this, getString(R.string.permissionDenied), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }


    protected abstract void initCreateView(Bundle savedInstanceState);

    public abstract Act initActivity();

    // 实例化presenter
    public abstract T initPresenter();


    private class MyHandler extends Handler {
        WeakReference<BaseMvpTestActivity> mMainActivityWeakReference;

        MyHandler(BaseMvpTestActivity mHomeActivity) {
            mMainActivityWeakReference = new WeakReference<>(mHomeActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            final BaseMvpTestActivity mHomeActivity = mMainActivityWeakReference.get();
            if (mHomeActivity != null) {
                switch (msg.what) {

                    case SCAN_LIST:
                        onMessageEvent();
                        break;
                    case DO_SCAN:
                        BleController.getInst().scanDevice();
                        break;

                }
            }
        }
    }


    /**
     * 27
     * 弹出系统弹框提示用户打开 Bluetooth
     * 28
     */

    private void turnOnBluetooth() {
        // 请求打开 Bluetooth
        Intent requestBluetoothOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

        // 设置 Bluetooth 设备可以被其它 Bluetooth 设备扫描到

        requestBluetoothOn.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        // 设置 Bluetooth 设备可见时间
        requestBluetoothOn.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, BLUETOOTH_DISCOVERABLE_DURATION);
        // 请求开启 Bluetooth
        this.startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("onActivityResult", "requestCode" + requestCode + "==" + resultCode);
        // requestCode 与请求开启 Bluetooth 传入的 requestCode 相对应
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON) {
            switch (resultCode) {
                // 点击确认按钮
                case 120: {
//                    // TODO 用户选择开启 Bluetooth，Bluetooth 会被开启
                    showkProgress(R.string.bluetooth_scan);
                    mHandle.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mHandle.obtainMessage(DO_SCAN).sendToTarget();
                        }
                    }, 2000);


                }
                break;
                // 点击取消按钮或点击返回键

                case android.app.Activity.RESULT_CANCELED:
                    // TODO 用户拒绝打开 Bluetooth, Bluetooth 不会被开启
                    showsAlert(R.string.bluetooth_op, false);

                    break;

                default:

                    break;

            }

        }
    }

}
